import mineflayer from "mineflayer";
import minecraftData from "minecraft-data";
import { pathfinder } from "mineflayer-pathfinder";
import { plugin as pvp } from "mineflayer-pvp";
import { loader as autoEat } from "mineflayer-auto-eat";
import { plugin as collectBlock } from "mineflayer-collectblock";
import plugin from "mineflayer-armor-manager";
const arrmorManager = plugin;

import { Bot } from "../bot/Bot.js";
import { readFileSync, existsSync } from "fs";
import { BotConfig } from "../type/botConfigType.js";
import { OpenAI } from "../api/OpenAI.js";
import { ContentManager } from "../bot/ContentManager.js";
import { ActManager } from "../bot/ActManager.js";

export let mcVersion: string = null as any;
export let mcdata: minecraftData.IndexedData = null as any;

export function botInit(dataPath: string = "./bots/asistent", bot: Bot): void {
  console.log(`读取配置文件: ${dataPath}/config.json`);
  if (!existsSync(`${dataPath}/config.json`)) {
    throw new Error("Config file not found");
  }
  const config = JSON.parse(readFileSync(`${dataPath}/config.json`, "utf-8")) as BotConfig;
  bot._systemPrompt = readFileSync(`${dataPath}/persona.md`, "utf-8") ?? "";
  console.log(`读取配置文件: ${dataPath}/config.json 成功, 名称为${config.name}`);

  bot._aiapi = new OpenAI(config.model.chat);
  bot._messageDelay = config.messageDelayMS ?? 0;
  bot._content = new ContentManager(config.name ?? "Assistant", config.maxContents ?? 20);
  bot._botName = config.name;
  bot._content.summaryConfig(5, bot._aiapi); // 总结设置

  if (bot._bot) bot._bot.end();

  const mcBot = (bot._bot = mineflayer.createBot({
    host: "localhost",
    port: 25565,
    username: config.name ?? "Bot",
  }));

  bot._hiddenActString = config.hiddenActString ?? true;
  bot._actManager = new ActManager(bot);

  mcBot.loadPlugin(pathfinder);
  mcBot.loadPlugin(pvp);
  mcBot.loadPlugin(collectBlock);
  mcBot.loadPlugin(autoEat);
  mcBot.loadPlugin(arrmorManager);

  mcBot.once("spawn", () => {
    mcBot.autoEat.opts = {
      priority: "foodPoints",
      minHunger: 12,
      minHealth: 14,
      returnToLastItem: true,
      offhand: false,
      eatingTimeout: 3000,
      bannedFood: [
        "rotten_flesh",
        "pufferfish",
        "chorus_fruit",
        "poisonous_potato",
        "spider_eye",
        "chicken",
      ],
      strictErrors: true,
    };
    mcBot.autoEat.enableAuto();

    const initCommands = config.initCommands ?? [];
    for (const command of initCommands) mcBot.chat(command);
    bot._idlePos = mcBot.entity.position.clone();
  });

  mcBot.once("resourcePack", () => {
    mcBot.acceptResourcePack();
  });

  mcBot.once("login", () => {
    mcVersion = mcBot.version;
    mcdata = minecraftData(mcVersion);
  });
}
